function [t  ] =     generateSIFTSelfPlotCVSLatexnonlin(repeatEach,numparams )
% repeat sift generated fundamental matrix experiments for a number of
% times
close all
   fclose all

% create a directory
mtime=clock;

%test cases
%sequences={'bt','wadham','merton1','merton2','merton3','valbonne','castlep19','fountainp11','rathaus'};
sequences={'merton1','merton2'};
sequencesimg=cell(1,size(sequences,2));
% algorithms
AlgNames={'selfCalibUnrobust','selfCalibmultistart','puttestshere3','geometricSelfCalib','findRobustWeightsperfinal'};

flg=checkIfMethodsDirsExist(sequences,AlgNames);
if(flg==0)
    error(' dirs or algs were not there');
end


[curdirname]=findUniqueDirname('datafilesd', ['SIFTsubdir_m_' num2str(mtime(1,2)) '_d_' num2str(mtime(1,3)) '_h_' num2str(mtime(1,4)) '_s_' num2str(ceil(mtime(1,5))) '_v']);
fidglobals= fopen([ curdirname '/display.txt'  ], 'w');
fprintf(fidglobals,[' repeateach parameter was ' num2str(repeatEach) ' and numparams was ' num2str(numparams)]);



algrealnames=cell(1,size(AlgNames,2));

numalgs=size(AlgNames,2);
numsequences=size(sequences,2);
%initializing outputs

% the last element is the ground truth
answers=repmat({zeros(repeatEach,5)},numalgs+1,numsequences);
errors=repmat({zeros(repeatEach,2)}, numalgs+1,numsequences); % error matrix is : [focal error, optical center error, time]

nlanswers=repmat({zeros(repeatEach,5)},numalgs+1,numsequences);
nlerrors=repmat({zeros(repeatEach,2)}, numalgs+1,numsequences);

% add in stuff for creating the charts and save them automatically
for i=1:numsequences
        
      % [corrs, ims, ~,ks, F, ~, ~,~,~,~,~,~,width,height] = readCorrsOxford(sequences{i}, 0.5,1,4,0);

      
    for j=1:repeatEach
        
            display(['for sequence: ' sequences{i} ' at ' num2str(repeatEach) ' reps left and '  num2str(numsequences-i) 'sequences are left']);
        [ F,corrs,FN,CRN,ks,height,width ,~,ims] = generateFImages(sequences{i},0, 0,0 );
         sequencesimg{1,i}=ims{1,1};
         
        if(size(F,2)==0)
            display(['sequence '  sequences{i} ' is empty']);
            fprintf(fidglobals,['******************sequence '  sequences{i} ' is empty']);
            continue;
        end

        % actual answers
        answers{numalgs+1,i}(j,:)= convertKtoVec(ks{1});
        [errf, errOC  ] = calcSelfCalibError([ks{1}(1,1) ks{1}(2,2)],[ks{1}(1,3) ks{1}(2,3)] ,ks);
        errors{numalgs+1,i}(j,:)= [errf errOC ];
        
        for k=1:numalgs
            
            tStart=tic;
            fh=str2func(AlgNames{k});
           [TKK,~,algrealnames{1,k}]=fh(F,width,height,numparams,corrs);
       algrealnames{1,k}=AlgNames{k};
           
            tElapsed = toc(tStart);
            
            [errf, errOC  ] = calcSelfCalibError([TKK(1,1) TKK(2,2)],[TKK(1,3) TKK(2,3)] ,ks);
            errors{k,i}(j,:)= [errf errOC ];
            answers{k,i}(j,:)= convertKtoVec(TKK);
            textdisp=[' algorithm ' AlgNames{k} ' on sequence ' sequences{i} ' trial ' num2str(j) ' had focal error ' num2str(errf) ' and OC error ' num2str(errOC )  ' had results ' num2str(TKK(1,1)) '  ' num2str(TKK(2,2)) '  ' num2str(TKK(1,3)) '  '  num2str(TKK(2,3)) '  '  num2str(TKK(1,2)) ];
            
            disp(textdisp);fprintf(fidglobals,[textdisp '\n']);
     
     
           [TKK,~,algrealnames{1,k}]=fh(FN,width,height,numparams,CRN);

            
            [errf, errOC  ] = calcSelfCalibError([TKK(1,1) TKK(2,2)],[TKK(1,3) TKK(2,3)] ,ks);
            nlerrors{k,i}(j,:)= [errf errOC ];
            nlanswers{k,i}(j,:)= convertKtoVec(TKK);
            textdisp=[' nonlin algorithm ' AlgNames{k} ' on sequence ' sequences{i} ' trial ' num2str(j) ' had focal error ' num2str(errf) ' and OC error ' num2str(errOC )  ' had results ' num2str(TKK(1,1)) '  ' num2str(TKK(2,2)) '  ' num2str(TKK(1,3)) '  '  num2str(TKK(2,3)) '  '  num2str(TKK(1,2)) ];
            
            disp(textdisp);fprintf(fidglobals,[textdisp '\n']);
        
        end
        
    end
    
end

display(['written to directory: ' curdirname]);

scriptdir=[curdirname '/code/'];
mkdir(scriptdir);

copyfile('*.m',scriptdir);
save([curdirname '/finalspace.mat ']);
fclose(fidglobals);
t =0;
for i=1:numsequences
    imwrite(sequencesimg{1,i},[curdirname '/' sequences{i} '.jpg'],'jpg' );
    system([ 'convert  ' curdirname '/' sequences{i} '.jpg  -resize 120x80!  ' curdirname '/' sequences{i} '.eps']);
end
writeData(answers,errors,algrealnames,sequences,curdirname,repeatEach,numsequences,numalgs,'regular');
writeData(nlanswers,nlerrors,algrealnames,sequences,curdirname,repeatEach,numsequences,numalgs,'nonlin');
end
function [d]= convertKtoVec(K)

d= [K(1,1) K(2,2) K(1,3) K(2,3) K(1,2)  ];

end
function []= writeData(answers,errors,AlgNames,sequences,dirname,repeatEach,numsequences,numalgs,prefix)
measures={'mean','std'};
quantits={'focal_length','aspect_ratio','x_center','y_center','skew', 'focal_length_error','optical_center_error'};
quantitsform={'$f_x$','$f_y$','$u_c$','$v_c$','s', 'f er','oc err'};
answersgraph=repmat({zeros(numsequences,numalgs+1)},size(measures,2),size(quantits,2));

answersheader=['sequence , iteration , algorithm ,   focal error , OC error ,  f_1 ,  f_2 ,  x ,  y ,  s  \n '];
com=' , ';


fid = fopen([ dirname '/' prefix 'answers.csv'  ], 'w');
fprintf(fid,answersheader);


for i=1:numsequences
    for k=1:numalgs
        for j=1:repeatEach
            fprintf(fid, [ sequences{i} com num2str(j) com  AlgNames{k} com  num2str(errors{k,i}(j,1)) com  num2str(errors{k,i}(j,2)) com  num2str(answers{k,i}(j,1)) com  num2str(answers{k,i}(j,2)) com  num2str(answers{k,i}(j,3)) com  num2str(answers{k,i}(j,4)) com  num2str(answers{k,i}(j,5)) '\n' ]);
        end
    end
end

fclose(fid);

for i=1:numsequences
    for k=1:(numalgs+1)
        % focal length
        answersgraph{1,1}(i,k)= mean(answers{k,i}(:,1));
        answersgraph{2,1}(i,k)= std(answers{k,i}(:,1));
        
        % aspect ratio
        answersgraph{1,2}(i,k)= mean(answers{k,i}(:,2));
        answersgraph{2,2}(i,k)= std(answers{k,i}(:,2));
        
        % xcenter
        answersgraph{1,3}(i,k)= mean(answers{k,i}(:,3));
        answersgraph{2,3}(i,k)= std(answers{k,i}(:,3));
        
        
        % ycenter
        answersgraph{1,4}(i,k)= mean(answers{k,i}(:,4));
        answersgraph{2,4}(i,k)= std(answers{k,i}(:,4));
        
        
        % skew
        answersgraph{1,5}(i,k)= mean(answers{k,i}(:,5));
        answersgraph{2,5}(i,k)= std(answers{k,i}(:,5));
        
        % focal error
        answersgraph{1,6}(i,k)= mean(errors{k,i}(:,1));
        answersgraph{2,6}(i,k)= std(errors{k,i}(:,1));
        
        %optical center error
        answersgraph{1,7}(i,k)= mean(errors{k,i}(:,2));
        answersgraph{2,7}(i,k)= std(errors{k,i}(:,2));
    end
end

headerstr='sequence  ';
for k=1:numalgs
    headerstr=[headerstr ' , '  AlgNames{k} ];
end
headerstr=[headerstr ' \n '];

tablestyle1(answersgraph,[dirname  '/' prefix 'tables1.tex'],sequences,AlgNames  );
tablestyle2(answersgraph,[dirname  '/' prefix 'tables2.tex'],sequences,AlgNames,quantitsform );
fid1 = fopen([ dirname '/' prefix 'graphstextikz.tex'  ], 'w');
fprintf(fid1,['\\documentclass{article} \n\\usepackage{times}\\usepackage{multirow} \n \\usepackage{amsmath} \n \\usepackage{amsfonts} \n \\usepackage{tikz,pgfplots} \n \\pgfplotsset{yticklabel style={text width=3em,align=right}} \n \\usepackage{graphicx} \n  \n\\begin{document}\n']);
fprintf(fid1,['\\input{' prefix 'tables1.tex}\n']);
fprintf(fid1,['\\input{' prefix  'tables2.tex}\n']);

for q=1:size(quantits,2)
    for p=1:size(measures,2)
        %        figure('Visible','off')
        bar(answersgraph{p,q});
        title([measures{1,p} ' of ' quantits{1,q}]);
        ylabel(quantits{1,q});
        legend(AlgNames,'Location','EastOutside');
        %       set(gca,'xticklabel',sequences);
        
        matlab2tikz( [dirname  '/' prefix 'graph' measures{1,p} '_' quantits{1,q} '.tikz'] );
        writeBarPGF2(answersgraph{p,q},[dirname  '/' prefix 'graph' measures{1,p} '_' quantits{1,q} '2.tikz'],measures{1,p} ,quantits{1,q},sequences,AlgNames  );
        
        fprintf(fid1,['\n\n\\begin{figure} \n \\centering \n ']);
        fprintf(fid1,['\\input{' prefix 'graph' measures{1,p} '_' quantits{1,q} '2.tikz}\n']);
        fprintf(fid1,['\\caption{' prefix 'graph' measures{1,p} ' $' quantits{1,q} '$ 2.tikz} \n \\end{figure} \n']);
        fid = fopen([ dirname '/' prefix 'answers' measures{1,p} '_' quantits{1,q} '.csv'  ], 'w');
        fprintf(fid,headerstr);
        
        for i=1:numsequences
            fprintf(fid,[sequences{1,i} ' , ']);
            for k=1:numalgs
                fprintf(fid,[num2str(answersgraph{p,q}(i,k)) ' , ']);
            end
            fprintf(fid,[' \n ']);
        end
        
        fclose(fid);
        %       pause
        close all
    end
end
fprintf(fid1,['\\end{document}']);
fclose(fid1);


oldFolder = cd(dirname);
compiletexf([prefix 'graphstextikz.tex']);

cd( oldFolder );
end


function [] = compiletexf(fname)
[pathstr, name, ext] = fileparts(fname);
system(['latex  ' fname]);
system(['dvips  ' name '.dvi']);
system(['ps2pdf  ' name '.ps ' name '.pdf']);


end



function []=  writeBarPGF(data,fname,measurename ,quantitname,sequences,AlgNames )


fid = fopen(fname, 'w');



numsequences=size(sequences ,2);
numalgs=size(AlgNames,2);

xticktext='';
for i=1:numsequences
    xticktext=[xticktext  sequences{1,i}  ];
    if(i~=numsequences)
        xticktext=[ xticktext  ','];
    end
end




% configures `bar shift'

fprintf(fid,['\\begin{tikzpicture}\n']);
fprintf(fid,['\\begin{axis}[\npoint meta=explicit symbolic,\nlegend pos=outer north east,\nybar, ymin=0,  enlarge x limits=0.2,\n']);
fprintf(fid,['ylabel={' measurename ' of ' strrep(quantitname, '_', ' ') '},\n']);
fprintf(fid,['symbolic x coords={' xticktext '},\n']);
fprintf(fid,['xtick=data,\n']);
fprintf(fid,['nodes near coords,\n']);
fprintf(fid,['every node near coord/.append style={font=\\tiny},\n']);
fprintf(fid,['nodes near coords align={vertical},\n]\n']);


% fprintf(fid,['\\begin{axis}[\n%%small,\nybar,']);
% fprintf(fid,['%%=8pt, %% configures ''bar shift''\nenlargelimits=0.15,\n']);
% fprintf(fid,['ylabel={index},\nsymbolic x coords={' xticktext '},\n']);
% fprintf(fid,['%%xtick=data,\n%%tick label\nstyle={font=\\footnotesize},\n']);
% fprintf(fid,['legend style={at={(0.5,-0.15)},\nanchor=north,legend columns=-1},\n']);
% fprintf(fid,['nodes near coords,\nevery node near coord/.append style={font=\\tiny},\n']);
% fprintf(fid,['nodes near coords align={vertical},\n]\n']);
legendtext='';
for k=1:numalgs
    legendtext=[legendtext  AlgNames{1,k}  ];
    if(k~=numalgs)
        legendtext=[legendtext  ' , '];
    end
    fprintf(fid,['\\addplot  coordinates {']);
    for i=1:numsequences
        fprintf(fid,[' (' sequences{1,i} ',' num2str(data(i,k)) ') [' num2str(round(data(i,k))) ']' ]);
    end
    fprintf(fid,['};\n']);
end

fprintf(fid,['\\legend{ ' strrep(legendtext, '_', ' ')   '}\n\\end{axis}\n\\end{tikzpicture}']);

fclose(fid);
%title=\n\\caption{' measurename ' of '  strrep(quantitname, '_', ' ')   ' }\n\\end{figure}\n\n\n\n\n\n
end


function []=  writeBarPGF2(data,fname,measurename ,quantitname,sequences,AlgNames )


fid = fopen(fname, 'w');



numsequences=size(sequences ,2);
numalgs=size(AlgNames,2);

xticktext='';
for i=1:numsequences
    xticktext=[xticktext  sequences{1,i}  ];
    if(i~=numsequences)
        xticktext=[ xticktext  ','];
    end
end



fprintf(fid,['\\begin{tikzpicture}\n']);
fprintf(fid,['\\begin{axis}[xbar,\nbar width=0.2cm,\nlegend style={at={(0.5,-0.15)},\nenlarge x limits={upper,value=0.19},\nxmin=0,xmax=100,\nanchor=north,legend columns=-1},\nylabel={' measurename ' of ' strrep(quantitname, '_', ' ') '},\nheight=17cm,\nwidth=12cm,\nsymbolic y coords={' xticktext '},\nyticklabel style={  rotate=45 },\nyticklabel pos=right,\nytick=data,\nnodes near coords,\nnodes near coords align=horizontal,\n]\n']);    
legendtext='';
for k=1:numalgs
    legendtext=[legendtext  AlgNames{1,k}  ];
    if(k~=numalgs)
        legendtext=[legendtext  ' , '];
    end
    fprintf(fid,['\\addplot  coordinates {']);
    for i=1:numsequences
        fprintf(fid,[' (' num2str(data(i,k)) ',' sequences{1,i}  ') [' num2str(round(data(i,k))) ']' ]);
    end
    fprintf(fid,['};\n']);
end

fprintf(fid,['\\legend{ ' strrep(legendtext, '_', ' ')   '}\n\\end{axis}\n\\end{tikzpicture}']);

fclose(fid);
%title=\n\\caption{' measurename ' of '  strrep(quantitname, '_', ' ')   ' }\n\\end{figure}\n\n\n\n\n\n
end

function []=  tablestyle1(data,fname,sequences,AlgNames )

fid = fopen(fname, 'w');


numsequences=size(sequences ,2);
numalgs=size(AlgNames,2);


headercol=' | l | ';
headernames=' Algorithm   ';
for i=1:numalgs
    headercol=[headercol ' l | '];
    headernames=[ headernames ' & ' AlgNames{1,i}  ];
end
headernames=[ headernames ' & ground truth  \\\\ \\hline\n'];
fprintf(fid,['\\begin{table}[h]\\footnotesize\n\\begin{center}\n\\begin{tabular}{ | l ' headercol '} \n \\hline \n' headernames]);

for i=1:numsequences
    fprintf(fid,[sequences{1,i} ' & ' ]);
    for k=1:numalgs
        
        fprintf(fid,['$\\begin{pmatrix} ' num2str(data{1,1}(i,k)) ' & ' num2str(data{1,5}(i,k)) ' & ' num2str(data{1,3}(i,k)) ' \\\\  0  & ' num2str(data{1,1}(i,k)*data{1,2}(i,k)) ' & ' num2str(data{1,4}(i,k)) ' \\\\ 0 & 0 & 1  \\end{pmatrix}$   & ' ]);
    end
    fprintf(fid,['  $\\begin{pmatrix} ' num2str(data{1,1}(i,1+numalgs)) ' & ' num2str(data{1,5}(i,1+numalgs)) ' & ' num2str(data{1,3}(i,1+numalgs)) ' \\\\  0  & ' num2str(data{1,1}(i,1+numalgs)*data{1,2}(i,1+numalgs)) ' & ' num2str(data{1,4}(i,1+numalgs)) ' \\\\ 0 & 0 & 1  \\end{pmatrix}$  \\\\ \\hline\n']);
    
end

fprintf(fid,['\n\\end{tabular}\n\\end{center}\n\\end{table}']);

fclose(fid);

end

function []=  tablestyle2(data,fname,sequences,AlgNames,quantits )

fid = fopen(fname, 'w');


numsequences=size(sequences ,2);
numalgs=size(AlgNames,2);
numvars=4;

headercol=' |  l | ';
headernames=' sequence & quantity     ';
for i=1:numalgs
    headercol=[headercol ' l | '];
    headernames=[ headernames ' & ' AlgNames{1,i}  ];
end
headernames=[ headernames '   \\\\ \\hline \\hline\n'];
fprintf(fid,['\\begin{table}[h]\\footnotesize\n\\begin{center}\n\\begin{tabular}{ | c |' headercol '} \n \\hline \n' headernames]);

for i=1:numsequences
    fprintf(fid,[' ' sequences{1,i} '  ']);
    
    for q=1:numvars
        
        if(q==2)
            fprintf(fid,['\\multirow{' num2str(numvars-1) '}{*}{ \\includegraphics[width=0.1\\textwidth]{' sequences{1,i} '.eps} }    ']);
        end
        fprintf(fid,[ ' & ' quantits{1,q} ' $=$ ' num2str(data{1,q}(i,1+numalgs),'%2.2f') ]);
        
        for k=1:numalgs
            
            fprintf(fid,[ ' & ' num2str(data{1,q}(i,k),'%2.2f')   ]);
        end
        
        if(q==numvars )
            fprintf(fid,[   ' \\\\ \\hline\n' ]);
        else
            fprintf(fid,[   '  \\\\ \n' ]);
        end
        
    end
    
end

fprintf(fid,['\n\\end{tabular}\n\\end{center}\n\\end{table}']);

fclose(fid);

end


